package com.laikan.reader.article.activity;

import android.content.Intent;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.laikan.library.components.activitys.BasicActivity;
import com.laikan.library.httpvolley.engine.HttpApiRequestEngine;
import com.laikan.library.httpvolley.engine.Requester;
import com.laikan.library.httpvolley.helper.RequestListener;
import com.laikan.library.httpvolley.helper.VolleyErrorHandler;
import com.laikan.library.httpvolley.response.HttpResponse;
import com.laikan.library.managers.ToastMgr;
import com.laikan.library.utils.SPUtil;
import com.laikan.reader.R;
import com.laikan.reader.article.adapter.BookFocusAdapter;
import com.laikan.reader.article.adapter.holder.BannerHolder;
import com.laikan.reader.article.adapter.holder.RecycleViewDivider;
import com.laikan.reader.comment.APIProtocol;
import com.laikan.reader.comment.Constants;
import com.laikan.reader.core.bean.BookFocusBean;
import com.laikan.reader.core.view.ProgressBar_Modern;
import com.laikan.reader.core.view.TipInfoLayout;
import com.socks.library.KLog;
import com.umeng.analytics.MobclickAgent;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;

/**
 * Created by Administrator on 2016/10/21.
 */
public class BookFocusActivity extends BasicActivity {

    private static final int END_LIST_PAGE = -1;
    private static final int PAGE_PULLDOWN_LIMIT_SIZE = 5;
    private static final int PAGE_PULLUP_LIMIT_SIZE = 10;
//    private HashSet mFocusDataItemIdList = new HashSet();
    private ArrayList<BookFocusBean.BookFocusDataList> refreshList = new ArrayList<BookFocusBean.BookFocusDataList>();
    private BookFocusAdapter bookFocusAdapter;
    private BookFocusBean result;
    private ArrayList<BookFocusBean.BookFocusDataList> bookFocusDataLists = new ArrayList<>();
    private ArrayList<BookFocusBean.Banner> bannerList = new ArrayList<>();

    protected RecyclerView bookfocus_recyclerview;
    protected TextView tv_title;
    protected ImageView iv_search;
    protected ProgressBar_Modern bottom_load_progressbar;
    private TipInfoLayout tipinfo;
    private SwipeRefreshLayout bookfocus_swiperefresh;
    private LinearLayoutManager mLinearLayoutManager;

    private int mCurrentPage;
    protected boolean mIsRequestDataFinish = true;
    private boolean mIsPullDownRefresh = true;
    private long mkeyTime;

    @Override
    protected void assignViews() {
        setContentView(R.layout.activity_bookfocus);
        iv_search = (ImageView)findViewById(R.id.iv_search);
        tv_title = (TextView)findViewById(R.id.tv_title);
        bookfocus_swiperefresh = (SwipeRefreshLayout)findViewById(R.id.bookfocus_swiperefresh);
        bookfocus_swiperefresh.setColorSchemeResources(R.color.C_66ccdd);
        bookfocus_recyclerview = (RecyclerView)findViewById(R.id.bookfocus_recyclerview);
        bottom_load_progressbar = (ProgressBar_Modern)findViewById(R.id.progressbar_modern);
        tipinfo = (TipInfoLayout)findViewById(R.id.tipinfo);
    }

    @Override
    protected void initData() {
//        bookfocus_swiperefresh.setEnabled(false);
        mLinearLayoutManager = new LinearLayoutManager(this);
        bookfocus_recyclerview.setLayoutManager(mLinearLayoutManager);
        bookfocus_recyclerview.addItemDecoration(new RecycleViewDivider(mContext, LinearLayoutManager.HORIZONTAL));

        bookFocusAdapter = new BookFocusAdapter(mContext, bookFocusDataLists, bannerList);
        bookFocusAdapter.setOnItemClickListener(onItemClickListener);
        bookFocusAdapter.setOnItemLongClickListener(onItemLongClickListener);

        bookfocus_recyclerview.setAdapter(bookFocusAdapter);
        mCurrentPage = 1;
        requestData(true, false);
    }

    public void requestData(final boolean isShowLoadingPage,boolean isPullDown) {
        int PAGE_LIMIT_SIZE;
        if (isPullDown){
            mCurrentPage = bookFocusDataLists.size() / PAGE_PULLDOWN_LIMIT_SIZE + 1;
            PAGE_LIMIT_SIZE = PAGE_PULLDOWN_LIMIT_SIZE;
        } else {
            mCurrentPage = bookFocusDataLists.size() / PAGE_PULLUP_LIMIT_SIZE + 1;
            PAGE_LIMIT_SIZE = PAGE_PULLUP_LIMIT_SIZE;
        }
        HashMap<String, String> map = new HashMap<String, String>();
        map.put("pageNo", mCurrentPage + "");
        map.put("pageSize", PAGE_LIMIT_SIZE + "");
        map.put("sd", SPUtil.getString("token", ""));
        RequestListener requestListener = new RequestListener() {
            @Override
            public void onPreExecute() {
                KLog.e("---------volley onPreExecute!!!");
                mIsRequestDataFinish = false;
                if (isShowLoadingPage) { tipinfo.setLoading(); }
            }

            @Override
            public void onSuccess(HttpResponse httpResponse) {
                KLog.e("BookFocusActivity : httpResponse : " + httpResponse.responseContent);
                tipinfo.setHide();
                Gson gson = new Gson();
                Type type = new TypeToken<BookFocusBean>() {}.getType();
                try {
                    result = gson.fromJson(httpResponse.responseContent, type);
                    if (result != null) {
                        if (null == result.getResult() || !Constants.RESULT_OK.equals(result.getResult())) {
                            ToastMgr.showShortToast(result.getError_msg());
                        }else {
                            bannerList.clear();
                            bannerList.addAll(result.getBookFocusData().getBanner());
                            if (mIsPullDownRefresh) { //此处判断是下拉刷新还是上拉加载
                                bookFocusAdapter.updateData(updateListData(result.getBookFocusData().getBookFocusDataList()), bannerList);
                            }else {
                                bookFocusAdapter.updateData(loadMoreData(result.getBookFocusData().getBookFocusDataList()), bannerList);
                            }

                            if (result.getBookFocusData().getBookFocusDataList().size() == 0 && mCurrentPage == 1) {
                                tipinfo.setEmptyData(R.string.bookfocus_null_article, R.drawable.lk_no_collect);
                            }else if ((mIsPullDownRefresh && result.getBookFocusData()!= null
                                       && result.getBookFocusData().getBookFocusDataList() != null
                                       && result.getBookFocusData().getBookFocusDataList().size() < PAGE_PULLDOWN_LIMIT_SIZE)
                                      || (!mIsPullDownRefresh && result.getBookFocusData()!= null
                                          && result.getBookFocusData().getBookFocusDataList() != null
                                          && result.getBookFocusData().getBookFocusDataList().size()< PAGE_PULLUP_LIMIT_SIZE)) {
                                mCurrentPage = END_LIST_PAGE;
                            }else {
                                mCurrentPage = bookFocusDataLists.size() / PAGE_PULLDOWN_LIMIT_SIZE + 1;
                            }
                        }
                    }
                }catch (Exception e) {
                    if (isShowLoadingPage) { tipinfo.setLoadError(R.string.laikan_data_load_failed); }
                    e.printStackTrace();
                }
            }

            @Override
            public void onError(VolleyErrorHandler errorHandler) {
                if (isShowLoadingPage) {
                    tipinfo.setLoadError(R.string.laikan_network_anomaly);
                }else {
                    ToastMgr.showShortToast(R.string.laikan_network_anomaly);
                }
            }

            @Override
            public void onFinish() {
                bottom_load_progressbar.setHide();
                bookfocus_swiperefresh.setRefreshing(false);
                mIsRequestDataFinish = true;
            }
        };

        Requester requester = new Requester();
        requester.setUrl(APIProtocol.laikan_bookfocus_article_list);
        requester.setMapBody(map);
        HttpApiRequestEngine.getInstance().httpPostRequest(requester, requestListener);
    }

    private ArrayList<BookFocusBean.BookFocusDataList> updateListData(ArrayList<BookFocusBean.BookFocusDataList> list) {
        for (int i = 0; i < list.size(); i++) {
//            if (!mFocusDataItemIdList.contains(list.get(i).getShorteId())) {
//                mFocusDataItemIdList.add(list.get(i).getShorteId());
                refreshList.add(list.get(i));
//            }
        }
        refreshList.addAll(bookFocusDataLists);
        bookFocusDataLists.clear();
        bookFocusDataLists.addAll(refreshList);
        refreshList.clear();
        return bookFocusDataLists;
    }

    private ArrayList<BookFocusBean.BookFocusDataList> loadMoreData(ArrayList<BookFocusBean.BookFocusDataList> list) {
        for (int i = 0; i < list.size(); i++) {
//            if (!mFocusDataItemIdList.contains(list.get(i).getShorteId())) {
//                mFocusDataItemIdList.add(list.get(i).getShorteId());
                bookFocusDataLists.add(list.get(i));
//            }
        }
        return bookFocusDataLists;
    }

    private BookFocusAdapter.OnItemClickListener onItemClickListener = new BookFocusAdapter.OnItemClickListener() {
        @Override
        public void onItemClick(View view, Object data) {
            if (data instanceof BookFocusBean.BookFocusDataList && data != null) {
                MobclickAgent.onEvent(mContext, "kd-sy-wz-dj");//精选-首页-文章-点击
                Intent intent = new Intent(mContext, BookFocusDetailActivity.class);
                //                intent.putExtra("articleId", ((BookFocusBean.BookFocusDataList)data).getShorteId());
                intent.putExtra("articleId", ((BookFocusBean.BookFocusDataList)data).getShorteId());
                startActivity(intent);
            }

//            ToastMgr.showLongToast("您点击了：  " + ((Book)data).getName() + "   作者： " + ((Book)data).getAuthorName());
        }
    };

    private BookFocusAdapter.OnItemLongClickListener onItemLongClickListener = new BookFocusAdapter.OnItemLongClickListener() {
        @Override
        public boolean onLongClick(View view, Object data) {
//            ToastMgr.showLongToast("您长按点击了：" + ((Book)data).getName() + "   作者： " + ((Book)data).getAuthorName());
            return false;
        }
    };

    @Override
    protected void setListener() {
        iv_search.setOnClickListener(this);
        tipinfo.setOnClick(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mIsPullDownRefresh = true;
                requestData(true, false);
            }
        });
        bookfocus_swiperefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener(){
            @Override
            public void onRefresh() {
                mIsPullDownRefresh = true;
                int firstVisibleItemPosition = mLinearLayoutManager.findFirstVisibleItemPosition();
                if (firstVisibleItemPosition == 0 && mCurrentPage == END_LIST_PAGE) {
                    ToastMgr.showShortToast(R.string.fw_data_all_load_done);
                    bookfocus_swiperefresh.setRefreshing(false);
                }else if(mIsRequestDataFinish){
                    requestData(false,true);
                }
            }
        });
        //RecyclerView滑动监听
        bookfocus_recyclerview.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                int lastVisibleItemPosition = mLinearLayoutManager.findLastVisibleItemPosition();
                if (lastVisibleItemPosition + 1 == bookFocusAdapter.getItemCount()) {
                    mIsPullDownRefresh = false;
                    if (mCurrentPage != END_LIST_PAGE && mIsRequestDataFinish) {
                        requestData(false, false);
                        bottom_load_progressbar.setShow();
                    }else if (mCurrentPage == END_LIST_PAGE) {
                        if(bookFocusDataLists.size() != 0){
                        bookFocusAdapter.setIsShowFooterView(true);
                        }
                    }
                }
            }
        });
    }

    @Override
    protected void onClickEvent(View view) {
        super.onClickEvent(view);
        switch (view.getId()) {
            case R.id.iv_search:
                Intent intent = new Intent(this, ArticleSearchActivity.class);
                startActivity(intent);
                break;
            default:
                break;
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        sendLoopPicReceiver(true);
    }

    @Override
    protected void onStop() {
        super.onStop();
        sendLoopPicReceiver(false);
    }

    private void sendLoopPicReceiver(boolean isLooper) {
        Intent intent = new Intent();
        intent.setAction(BannerHolder.LooperepicAction);
        intent.putExtra("isLooperPic", isLooper);
        sendBroadcast(intent);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        // 2秒内连续按两次 退出程序
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if ((System.currentTimeMillis() - mkeyTime) > 2000) {
                mkeyTime = System.currentTimeMillis();
                Toast.makeText(this, R.string.personal_exit_program, Toast.LENGTH_SHORT).show();
            }else {
                finish();
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
}